package com.aishua.fire.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aishua.fire.common.IdUtil;
import com.aishua.fire.entity.account.Session;
import com.aishua.fire.entity.addressBook.AddressBookInfo;
import com.aishua.fire.entity.app.APPExerciseConclusionReqInfo;
import com.aishua.fire.entity.app.APPExerciseFeedBack;
import com.aishua.fire.entity.app.APPExerciseFeedBack_Detail;
import com.aishua.fire.entity.app.App_AddPlanRecordInfo;
import com.aishua.fire.entity.app.App_AddressBookInfo;
import com.aishua.fire.entity.app.App_CheckItemInfo;
import com.aishua.fire.entity.app.App_PlanRecordInfo;
import com.aishua.fire.entity.app.GetAppOrganizationAndUserInfo;
import com.aishua.fire.entity.checkitem.CheckItemDetailInfo;
import com.aishua.fire.entity.checkitem.CheckItemInfo;
import com.aishua.fire.entity.drillrecord.App_DrillRecordCatalogList;
import com.aishua.fire.entity.drillrecord.DrillRecordExampleDetailInfo;
import com.aishua.fire.entity.drillrecord.DrillRecordExampleInfo;
import com.aishua.fire.entity.material.MaterialAddressList;
import com.aishua.fire.entity.material.MaterialDetailRecordInfo;
import com.aishua.fire.entity.material.MaterialDetailRecordInfoList;
import com.aishua.fire.entity.material.MaterialDetailsList;
import com.aishua.fire.entity.material.MaterialStandardList;
import com.aishua.fire.entity.organization.OrganizationInfo;
import com.aishua.fire.mapper.AppOperationMapper;
import com.aishua.fire.mapper.CheckItemMapper;
import com.aishua.fire.mapper.DrillRecordMapper;
import com.aishua.fire.mapper.LoginMapper;
import com.aishua.fire.mapper.MaterialMapper;
import com.aishua.fire.mapper.OrganizationMapper;
import com.aishua.fire.service.AppOperationService;
import com.github.pagehelper.PageHelper;

@Service
public class AppOperationServiceImpl implements AppOperationService {

    @Autowired
    private DrillRecordMapper drillmapper;
    
	@Autowired
	private AppOperationMapper appMapper;

	@Autowired
	private LoginMapper loginMapper;
	
	@Autowired
	private OrganizationMapper organizationMapper;
	
	@Autowired
	private IdUtil idUtil;
	
	@Autowired
	private CheckItemMapper itemMapper;
	
    @Autowired
    private MaterialMapper materialMapper;
	
	
	/**
	 * 插入APP拨号记录
	 * @param user_id
	 * @param phone
	 */
	@Override
	public void insertCallRecord(String user_id, String phone) 
	{
		Map<String, String> pa = new HashMap<String, String>();
		pa.put("user_id", user_id);
		pa.put("phone", phone);
		appMapper.insertCallRecord(pa);
	}

	/**
	 * 通过sessionID查询用户ID
	 */
	@Override
	public Session findByAppSessionId(String sessionId) 
	{
		 return	loginMapper.findByAppSessionId(sessionId);
	}

	/**
	 * 查询APP拨号记录
	 * @param user_id
	 * @param phone
	 */
	@Override
	public List<App_AddressBookInfo> getCallRecord(String user_id, int pageNumber, int pageSize) 
	{
		PageHelper.startPage(pageNumber, pageSize);
		List<App_AddressBookInfo> list = appMapper.getCallRecord(user_id);
		for(App_AddressBookInfo info : list)
		{
			Map<String, String> pa = new HashMap<String, String>();
			pa.put("add_id", info.getId());
			pa.put("type", "1");
			String duty = appMapper.getOrganizationByAddressBookId(pa);
			pa.put("type", "2");
			String organs = appMapper.getOrganizationByAddressBookId(pa);
			info.setDutys(duty);	
			info.setOrganizations(organs);
		}
		return list;
	}

	/**
	 * 查询APP拨号记录数量
	 * @param user_id
	 * @param phone
	 */
	@Override
	public int listTotal(String user_id)
	{
		return appMapper.listTotal(user_id);
	}

	/**
	 * APP_查询当前组织结构下所有节点及员工
	 */
	@Override
	public GetAppOrganizationAndUserInfo getOrganizationAndUser(String id, int pageNumber, int pageSize)
	{
		PageHelper.startPage(pageNumber, pageSize);
		
		GetAppOrganizationAndUserInfo bean = new GetAppOrganizationAndUserInfo();
		
		List<AddressBookInfo> addressBooklist = organizationMapper.selectAddressBookInfoList(id);
		bean.setAddressBooklist(addressBooklist);
		int total = organizationMapper.getAddressTotal(id);
		bean.setTotal(total);
		//根据父节点ID，查询子节点ID
		List<OrganizationInfo> organlist = organizationMapper.selectOrganizationByF_id(id);
		bean.setOrganlist(organlist);
		return bean;
	}

	/**
	 * 根据通讯录ID，查询通讯录详情
	 */
	@Override
	public App_AddressBookInfo getAddressBookDetail(String id) 
	{
		App_AddressBookInfo info = appMapper.getAddressBookDetail(id);
		Map<String, String> pa = new HashMap<String, String>();
		pa.put("add_id", id);
		pa.put("type", "1");
		String duty = appMapper.getOrganizationByAddressBookId(pa);
		pa.put("type", "2");
		String organs = appMapper.getOrganizationByAddressBookId(pa);
		info.setDutys(duty);	
		info.setOrganizations(organs);
		return info;
	}
	
	
	/**
	 * APP_查询通讯录
	 * @param parm
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
	@Override
	public List<App_AddressBookInfo> getAddressBookList(String parm, int pageNumber, int pageSize) 
	{
		PageHelper.startPage(pageNumber, pageSize);
		Map<String, String> pp = new HashMap<String, String>();
		Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");  
        if(StringUtils.isNotBlank(parm))
        {
        	if(pattern.matcher(parm).matches())
        	{
        		pp.put("phone", parm);
        		pp.put("name", "");
        	}
        	else
        	{
        		pp.put("phone", "");
        		pp.put("name", parm);
        	}
        	
        }
        else
        {
        	pp.put("phone", parm);
        	pp.put("name", parm);
        }
		
		List<App_AddressBookInfo> list = appMapper.getAddressBookList(pp);
		for(App_AddressBookInfo info : list)
		{
			Map<String, String> pa = new HashMap<String, String>();
			pa.put("add_id", parm);
			pa.put("type", "1");
			String duty = appMapper.getOrganizationByAddressBookId(pa);
			pa.put("type", "2");
			String organs = appMapper.getOrganizationByAddressBookId(pa);
			info.setDutys(duty);	
			info.setOrganizations(organs);
		}
		
		return list;
	}
	
	/**
	 * 查询APP拨号记录数量
	 * @param user_id
	 * @param phone
	 */
	@Override
	public int getAddressBookListTotal(String parm)
	{
		Map<String, String> pp = new HashMap<String, String>();
		Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");  
        if(StringUtils.isNotBlank(parm))
        {
        	if(pattern.matcher(parm).matches())
        	{
        		pp.put("phone", parm);
        		pp.put("name", "");
        	}
        	else
        	{
        		pp.put("phone", "");
        		pp.put("name", parm);
        	}
        	
        }
        else
        {
        	pp.put("phone", parm);
        	pp.put("name", parm);
        }
		
		return appMapper.getAddressBookListTotal(pp);
	}
	
	public static void main(String[] args) {
		String str = "";
	        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");  
	        System.out.println(pattern.matcher(str).matches()); 
	}

	/**
	 * 查询参数表
	 */
	@Override
	public String getparameterinfo(String parm) 
	{
		return appMapper.getparameterinfo(parm);
	}

	@Override
	public App_PlanRecordInfo app_planSweep(String s_id, String user_id) 
	{
		//主键ID
		String uuid= idUtil.getAllId();
		//查询巡检点信息
		App_PlanRecordInfo info = appMapper.getCheckManagerPoint(s_id);
		Map<String, String> pa = new HashMap<String, String>();
		pa.put("s_id", s_id);
		pa.put("user_id", user_id);
		pa.put("uuid", uuid);
		//插入扫码记录
		appMapper.insertSaoMaRecord(pa);
		info.setRecord_id(uuid);
		//查询当前巡检点下的所有巡检项目
		List<CheckItemInfo> list = appMapper.getCheckItemList(s_id);
		for(CheckItemInfo checkinfo : list)
		{
			//只有选择检查有检查项目
			if("1".equals(checkinfo.getItem_type()))
			{
				//查询检查项目关联的检查明细
				List<CheckItemDetailInfo> details = itemMapper.getCheckItemDetail(checkinfo.getId());
				checkinfo.setDetails(details);
			}
			//查询检查项目对象关联的图片
			List<String> pics = itemMapper.getCheckItemAndPic(checkinfo.getId());
			checkinfo.setPics(pics);
		}
		info.setCheckItems(list);
		return info;
	}

    /**
     * APP_查询应急物资列表
     * @param user_id
     * @param address_id
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @Override
    public List<MaterialDetailsList> materiallist(String user_id, String address_id, int pageNumber, int pageSize) 
    {
        PageHelper.startPage(pageNumber, pageSize);
        Map<String, String> pp = new HashMap<String, String>();
        pp.put("user_id", user_id);
        pp.put("address_id", address_id);
        
        List<MaterialDetailsList> list = appMapper.materiallist(pp);
        for(MaterialDetailsList bean : list)
        {
            List<String> strs = itemMapper.getCheckItemAndPic(bean.getM_id());
            bean.setPics(strs);
        }
        return list;
    }

    /**
     * APP_查询应急物资列表条数
     * @param user_id
     * @param m_name
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @Override
    public int materiallistTotal(String user_id, String m_name) 
    {
        Map<String, String> pp = new HashMap<String, String>();
        pp.put("user_id", user_id);
        pp.put("m_name", m_name);
        return appMapper.materiallistTotal(pp);
    }

    /**
     * APP_插入用户物资巡检记录
     */
    @Override
    public boolean insertMaterialRecord(MaterialDetailRecordInfo info) 
    {
        int s = 0;
        appMapper.insertMaterialRecord(info); 
        if(!"1".equals(info.getType()))
        {
            //根据物资信息ID，查询物资信息对象中的数量
            MaterialDetailsList bean = appMapper.getMaterialBean(info.getMaterial_detail_id());
            if("2".equals(info.getType()))
            {
                s = Integer.valueOf(bean.getQuantity()) + Integer.valueOf(info.getNum());
            }
            else if("3".equals(info.getType()))
            {
                //如果传入数量大于原有数量，直接报错
                if(Integer.valueOf(bean.getQuantity()) < Integer.valueOf(info.getNum()))
                {
                    return false;
                }
                else
                {
                    s = Integer.valueOf(bean.getQuantity()) - Integer.valueOf(info.getNum());
                }
            }
            bean.setQuantity( s + "");
            
            appMapper.updateMaterialBean(bean);
        }
        return true;
    }

    /**
     * APP_记录二维码扫描记录_插入巡检点项目提交记录
     */
    @Override
    public void app_addPlanSweep(App_AddPlanRecordInfo addInfo)
    {
        //补充巡检点巡检信息
        appMapper.updatePlanRecord(addInfo);
        //插入巡检项目明细信息
       for(App_CheckItemInfo info : addInfo.getItems()) 
       {
           info.setRecord_id(addInfo.getRecord_id());
           appMapper.insertPlanRecordDetail(info);
       }
       Map<String, String> pa = new HashMap<String, String>();
       pa.put("itemId", addInfo.getRecord_id());
       for(String str : addInfo.getPic())
       {
           pa.put("picurl", str);
           materialMapper.insertCheckItemAndPic(pa);
       }
    }

    /**
     * app查询_物资管理-查询当前登录员工所有物资储存地点
     * @param pageNumber
     * @param pageSize
     * @param user_id
     * @return
     */
    @Override
    public List<MaterialAddressList> getMaterialAddressByApp(int pageNumber, int pageSize, String user_id) 
    {

        PageHelper.startPage(pageNumber, pageSize);
        return appMapper.getMaterialAddressByApp(user_id);
    }

    /**
     * APP_查询用户物资巡检记录列表
     * @param user_id
     * @return
     */
    @Override
    public List<MaterialDetailRecordInfo> getMaterialRecordList(String user_id, int pageNumber, int pageSize)
    {
        PageHelper.startPage(pageNumber, pageSize);
        return appMapper.getMaterialRecordList(user_id);
    }

    /**
     * APP_查询用户物资巡检记录详情接口
     * @param id
     * @return
     */
    @Override
    public MaterialDetailRecordInfoList getMaterialRecordDetail(String recode_id)
    {
        MaterialDetailRecordInfoList bean = appMapper.getMaterialRecordDetail(recode_id);
        List<MaterialStandardList> materialStandards = appMapper.getMaterialStandardList(bean.getMaterial_id());
        bean.setMaterialStandards(materialStandards);
        return bean;
    }

    /**
     * app查询_演练资料详情接口计划_演练现场记录
     * @param type
     * @return
     */
    @Override
    public List<App_DrillRecordCatalogList> dataDrillRecord(String type) 
    {
        //根据类型查询所有目录
        List<App_DrillRecordCatalogList> list = appMapper.getCatalogList(type);
        for(App_DrillRecordCatalogList bean : list)
        {
            List<DrillRecordExampleInfo> exlist = drillmapper.exampleList(bean.getId());
            if(exlist.size() < 1)
            {
                list.remove(bean);
            }
            else
            {
              //查询题目选项明细
                for(DrillRecordExampleInfo info : exlist)
                {
                    List<DrillRecordExampleDetailInfo> details = drillmapper.getExampleDetailsList(info.getId());
                    info.setDetails(details);
                }
                bean.setExampleList(exlist);
            }
        }
        
        return list;
    }

    /**
     * 
     */
    @Override
    public List<App_DrillRecordCatalogList> dataDrillRecordAnswer(String id) 
    {
        //查询演练计划类型
        String type = appMapper.getPlanType(id);

      //根据类型查询所有目录
        List<App_DrillRecordCatalogList> list = appMapper.getCatalogList(type);
        
        Map<String, String> pa = new HashMap<String, String>();
        pa.put("p_id", id);
        
        for(App_DrillRecordCatalogList bean : list)
        {
            
            List<DrillRecordExampleInfo> exlist = drillmapper.exampleList(bean.getId());
            //查询题目选项明细
            for(DrillRecordExampleInfo info : exlist)
            {
                pa.put("e_id", info.getId());
                //查询题目的选中答案
                String chooseId = appMapper.getExampleAnswer(pa);
                List<DrillRecordExampleDetailInfo> details = drillmapper.getExampleDetailsList(info.getId());
                info.setDetails(details);
                info.setChooseDetailsId(chooseId);
            }
            bean.setExampleList(exlist);
        }
        
        return list;
    }

    /**
     * app查询_演练资料详情接口计划_查询预案演练总结
     */
    @Override
    public APPExerciseConclusionReqInfo dataExist_ques(String p_id) 
    {
        return appMapper.getConclusionReqInfo(p_id);
    }

    /**
     * app查询_演练资料详情接口计划_插入演练反馈
     */
    @Override
    public void exist_feedback(APPExerciseFeedBack feedback) 
    {
        for(APPExerciseFeedBack_Detail detail : feedback.getFeedback())
        {
            String id = idUtil.getAllId();
            detail.setP_id(feedback.getP_id());
            detail.setUser_id(feedback.getUser_id());
            detail.setId(id);
            appMapper.insertFeedBackDetail(detail); 
            for(String url : detail.getImageArray())
            {
                Map<String, String> pa = new HashMap<String, String>();
                pa.put("itemId", id);
                pa.put("picurl", url);
                itemMapper.insertCheckItemAndPic(pa);
            }
        }
        
    }

    /**
     * app查询_演练资料详情接口计划_查询预案演练反馈
     */
    @Override
    public List<APPExerciseFeedBack_Detail> getExist_feedback(String p_id) 
    {
        List<APPExerciseFeedBack_Detail> list = appMapper.getExist_feedback(p_id);
        for(APPExerciseFeedBack_Detail info : list)
        {
            List<String> pics = itemMapper.getCheckItemAndPic(info.getId());
            info.setImageArray(pics);
        }
        return list;
    }
}
